    //
//  citipadMainViewController.m
//  citipad
//
//  Created by Chih Yuan Liu on 3/10/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "citipadMainViewController.h"
#import "formCityInfoViewController.h"
#import "CTPAlert.h"
#import "Reachability.h"
#import "constants.h"
#import "CTPCityModel.h"
#import "CTPCity.h"
#import "flickrFirstGrabber.h"
#import "citipadCityViewController.h"
#import <QuartzCore/QuartzCore.h>

@implementation citipadMainViewController

@synthesize scrollView;
@synthesize addCityView;
@synthesize addCityHolder;

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

CTPCityModel *cityModel;
NSMutableArray *grabbers;
citipadCityViewController *cityView;

- (void) layoutContent{
	UIImageView *view = nil;
	NSArray *subviews = [scrollView subviews];
	
	// reposition all image subviews in a horizontal serial fashion
	int i = 0;
	for (view in subviews)
	{
		if ([view isKindOfClass:[UIView class]] && view.tag > 0)
		{
			CGFloat curYLoc = 200 * (i / 5);
			CGFloat curXLoc = 156 * (i % 5);
			CGRect frame = view.frame;
			frame.origin = CGPointMake(curXLoc, curYLoc);
			view.frame = frame;
			
			i++;
		}
	}
	
	// set the content size so it can be scrollable
	[scrollView setContentSize:CGSizeMake((10 * 100), [scrollView bounds].size.height+100)];
	
}

-(void)cleanContent{
	for(flickrFirstGrabber * grabber in grabbers){
		[grabber requireStop];
	}
	UIView * view;
	for(view in [scrollView subviews]){
		[view removeFromSuperview];
	}
}

-(void)dynamicAddCityView{
	if(cityModel != nil){

		int count = [cityModel GetCount];
		
		int const labelheight = 21;
		int const labelwidth = 140;
		int const imageheight = 140;
		int const imagewidth = 140;
		
		for (int i = 0; i < count; i++){
			CTPCity *city = [cityModel GetItemAtIndex:i];
			
			UIImage *image = [UIImage imageNamed:@"c0.png"];
			UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
			
			[imageView addGestureRecognizer:
			[[[UILongPressGestureRecognizer alloc] initWithTarget:self
													action:@selector(longPress:)] autorelease]];
			
			[imageView addGestureRecognizer:
			 [[[UITapGestureRecognizer alloc] initWithTarget:self
													  action:@selector(taponcity:)] autorelease]];

			UIView *holder = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 156, 200)];
			UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(9, 14 + imageheight + 9, labelwidth , labelheight)];
			label.tag = i;
			label.text = city.name;
			label.backgroundColor = [UIColor clearColor];
			// image frame
			CGRect rect = CGRectMake(9,14,imagewidth, imageheight);//imageView.frame;
			rect.size.height = imageheight;
			rect.size.width = imagewidth;
			holder.tag = (i+1);
			CGRect holderrect = holder.frame;
			holderrect.size.height = 200;
			holder.frame = holderrect;
			imageView.frame = rect;
			imageView.tag = i;	// tag our images for later use when we place them in serial fashion
			imageView.userInteractionEnabled = YES;
			[holder addSubview:imageView];
			[holder addSubview:label];
			[scrollView addSubview:holder];
			
			flickrFirstGrabber * grabber = [[flickrFirstGrabber alloc]initWithImageView: imageView];
			[grabber grabImage:city.imageKey fetchkey:city.name];
			[grabbers addObject:grabber];
			[grabber release];

			
			[imageView release];
			[holder release];
			[label release];
		}
		addCityHolder.tag = (count+1);
		[scrollView addSubview: addCityHolder]; //need to add to scrollview
		[self layoutContent];
	}
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	[addCityView addGestureRecognizer:
	 [[[UITapGestureRecognizer alloc] initWithTarget:self
											  action:@selector(onAddCityTouch)] autorelease]];
	
	cityModel = [[CTPCityModel alloc] init];
	
	grabbers = [[NSMutableArray alloc] init];
	
	[self dynamicAddCityView];
}


-(void)longPress:(UILongPressGestureRecognizer*)sender {
	if (sender.state == UIGestureRecognizerStateEnded) {
		//NSLog(@"Long press Ended");
		UIImageView * view = (UIImageView*)[(UITapGestureRecognizer*)sender view];
		NSLog(@"%d", view.tag);
		UIAlertView *alert  = [[[UIAlertView alloc] initWithTitle: @"Sure to remove this?"
														  message: @""
														 delegate: self
												cancelButtonTitle:@"Not Now"
												otherButtonTitles:@"OK", nil] autorelease];
		[alert show];
		curCityViewIndex = view.tag;
	}
	else {
		//NSLog(@"Long press detected.");
	}
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	if(buttonIndex ==1){
		CTPCity * city = [cityModel GetItemAtIndex:curCityViewIndex];
		[cityModel removeCity:city];
		[city release];
		[self cleanContent];
		[self dynamicAddCityView];
	}
}


-(void)taponcity:(UITapGestureRecognizer*)sender {
	UIImageView * view = (UIImageView*)[(UITapGestureRecognizer*)sender view];
	CTPCity * city = [cityModel GetItemAtIndex:view.tag];
	cityView = [[citipadCityViewController alloc] init];
	[cityView setName:city.name];
	[self presentModalViewController:cityView animated:YES];
}

- (void)viewDidAppear:(BOOL)animated{
	Reachability* hostReach;	
	NSString* ip = CitiportServerIP;
	hostReach = [[Reachability reachabilityWithHostName: ip] retain];
	[hostReach startNotifier];
	NetworkStatus netStatus = [hostReach currentReachabilityStatus];
	if(netStatus == NotReachable){
		[[CTPAlert instance] alert:@"Cannot connect to Citiport server" withMessage:@"some features will be disable!"];
	}
	[hostReach release];
	
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation ==
			UIInterfaceOrientationLandscapeLeft);
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
	[cityModel release];
	[grabbers release];
}


- (void)dealloc {
    [super dealloc];
}

formCityInfoViewController *formCity;

-(void) onAddCityTouch{
	formCity = [[formCityInfoViewController alloc] init];
	formCity.delegate = self;
	formCity.modalPresentationStyle = UIModalPresentationFormSheet;
	[self presentModalViewController:formCity animated:YES];
}

- (void)onOkTouch:(formCityInfoViewController*)sender name:(NSString*)name{
	CTPCity * city = [[CTPCity alloc] init];
	NSLog(@"%s, %@", __PRETTY_FUNCTION__, name);
	city.name = name;
	if(cityModel != nil){
		[cityModel addCity:city];
	}
	[city release];
	[self cleanContent];
	[self dynamicAddCityView];
}

-(void) onModalDismiss:(formCityInfoViewController *)sender{
	NSLog(@"close modal win");
}

@end
